package org.linitly.boot.base.handle;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.google.common.base.CaseFormat;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.linitly.boot.base.annotation.Dict;
import org.linitly.boot.base.service.SysDataDictItemCacheService;
import org.linitly.boot.base.utils.bean.SpringBeanUtil;

/**
 * @author: linitly
 * @date: 2020/12/6 11:42
 * @descrption:
 */
@Slf4j
public class DictSerialize extends StdSerializer<Object> implements ContextualSerializer {

    private final SysDataDictItemCacheService sysDataDictItemCacheService = SpringBeanUtil.getBean(SysDataDictItemCacheService.class);

    private String code;
    private String dictText;
    private String dictTextSuffix;

    protected DictSerialize() {
        super(Object.class);
    }

    protected DictSerialize(String code, String dictText, String dictTextSuffix) {
        super(Object.class);
        this.code = code;
        this.dictText = dictText;
        this.dictTextSuffix = dictTextSuffix;
    }

    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
        String currentName = jsonGenerator.getOutputContext().getCurrentName();
//        log.info("currentName：" + currentName);
        try {
            // 获取字典码，如果code属性值不为空，则为code属性值；否则为标注属性转驼峰后的值
            String dictCode = StringUtils.isNotBlank(this.code) ? this.code :
                    CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, currentName);
            // 获取翻译字典的属性名
            String dictFieldName = StringUtils.isBlank(this.dictText) ?
                    StringUtils.isBlank(this.dictTextSuffix) ? currentName : currentName + this.dictTextSuffix : this.dictText;
//            log.info("dictFieldName：" + dictFieldName);
            // 获取字典值
            String text = sysDataDictItemCacheService.getItemCache(dictCode, o.toString());
//            log.info("text：" + text);
            // 输出原属性的值
            jsonGenerator.writeObject(0);
            // 输出字典翻译
            jsonGenerator.writeStringField(dictFieldName, text);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("反序列化字典出错，字段名为：" + currentName);
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) {
        Dict annotation = beanProperty.getAnnotation(Dict.class);
        return new DictSerialize(annotation.code(), annotation.dictText(), annotation.dictTextSuffix());
    }
}
